package net.csdn.business.notify.handler.config;


import net.csdn.business.notify.common.config.properties.AsyncThreadPoolProperties;
import net.csdn.business.notify.common.domain.CustomTaskDecorator;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @ClassName HandlerThreadPoolConfig
 * @Description handler模块 线程池的配置
 * @Author zhangyl
 * @Date 2023/11/30 16:25
 */
public class HandlerThreadPoolConfig {

    private static final String PRE_FIX = "notify-chanel-";

    /**
     * 业务：处理某个渠道的某种类型消息的线程池
     * 配置：不丢弃消息，核心线程数不会随着keepAliveTime而减少(不会被回收)
     * 动态线程池且被Spring管理：true
     *
     * @return
     */
    public static ExecutorService getExecutor(String groupId, AsyncThreadPoolProperties properties) {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(properties.getCoreSize());
        executor.setMaxPoolSize(properties.getMaxSize());
        executor.setQueueCapacity(properties.getQueueCapacity());
        executor.setKeepAliveSeconds(properties.getKeepAlive());
        executor.setThreadNamePrefix(PRE_FIX + groupId+"-");
        executor.setTaskDecorator(new CustomTaskDecorator());
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 线程池对拒绝任务的处理策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 初始化
        executor.initialize();
        // 默认初始化所有核心线程
        executor.getThreadPoolExecutor().prestartAllCoreThreads();
        return executor.getThreadPoolExecutor();
    }


}
